﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skyhook.Core
{
    public class LoopInteger
    {
        public delegate void OnChangeEvent(int delta);
        public event OnChangeEvent OnChange;

        int Minimum = 0;
        int ValuesCount = 0;

        public LoopInteger(int minimum, int count)
        {
            Minimum = minimum;
            ValuesCount = count;
        }

        public int Value
        {
            get;
            private set;
        }

        public void Change(int delta)
        {
            int oldvalue = Value;

            Value += delta;

            IncrementIfBelowMinimum();
            DecrementIfAboveMaximum();

            CallOnChangeIfNesessary(oldvalue);
        }

        void IncrementIfBelowMinimum()
        {
            while (Value < Minimum)
            {

                Value += ValuesCount;
            }
        }
        
        void DecrementIfAboveMaximum()
        {
            while (Value > ValuesCount - 1)
            {
                Value -= ValuesCount;
            }
        }

        void CallOnChangeIfNesessary(int oldvalue)
        {
            if (Value != oldvalue && OnChange != null)
            {
                OnChange(Value);
            }
        }
    }
}
